from pyecharts import options as opts
from pyecharts.charts import Bar
import datas_fetch


def workTime_count():
    # # 计算当天设备工作时长数据列（'worktime'）的平均值，并将结果保留两位小数
    workTime_mean = round(datas_fetch.day_timeinfos['worktime'].mean(), 2)
    # 初始化变量 higher,low,count用来统计工作时长高于平均值、低于平均值和总设备数量。
    higher = 0; lower = 0; count = 0
    for i in datas_fetch.day_timeinfos['worktime']:
        if i < workTime_mean:
            lower += 1
        else:
            higher += 1
        count += 1
    # 绘制条形图
    bar = Bar(init_opts=opts.InitOpts(width='100%', height='420px'))  # 绘制的条形图的大小
    bar.add_xaxis(xaxis_data=['总', '低', '高'])  # 设置每个数据系列的颜色和间距
    bar.add_yaxis("总设备数量", y_axis=[count, 0, ], category_gap=5, itemstyle_opts=opts.ItemStyleOpts(color='#33ffff'))
    bar.add_yaxis("低于平均工作时长设备数", y_axis=[0, lower, ], category_gap=5,
        itemstyle_opts=opts.ItemStyleOpts(color='#9999ff'))
    bar.add_yaxis("高于平均工作时长设备数", y_axis=[0, 0, higher], category_gap=5,
        itemstyle_opts=opts.ItemStyleOpts(color='#33ff99'))
    # 设置图表的标题、图例、x轴样式和y轴样式。
    bar.set_global_opts(title_opts=opts.TitleOpts('设备工作效率统计（设备数统计）',title_textstyle_opts={"color": "white"}),
        legend_opts=opts.LegendOpts(
            is_show=True, pos_right='5', pos_top='20', orient='vertical', item_width=5,
            textstyle_opts=opts.TextStyleOpts(font_size=10, color="white"),
        ),
        xaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))
        ),
        yaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))
        )
    )
    # 图例的展示
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    bar.reversal_axis()
    return bar
